package com.uchiha.nova.core.tool.support;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uchiha.nova.core.tool.util.BeanUtil;
import com.uchiha.nova.core.tool.util.NumberUtil;
import com.uchiha.nova.core.tool.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 周林静
 * @version 1.0
 * @date 2020/10/28 14:12
 */
public class Condition {

    private final static Pattern SC_EXTRACTION = Pattern.compile("(?<field>[0-9a-zA-z]+)\\((?<sort>[0-9a-zA-z]+)\\)",
            Pattern.CASE_INSENSITIVE);
    /**
     * 转化成mybatis plus中的Page
     *
     * @param queryContext 查询条件
     * @return IPage
     */
    public static <T> IPage<T> getPage(QueryContext queryContext) {
        Page<T> page = new Page<>(NumberUtil.toInt(String.valueOf(queryContext.getCurrentPage()), 1), NumberUtil.toInt(String.valueOf(queryContext.getPageSize()), 10));
        String scsValue= queryContext.getScs();
        if (StringUtil.isNotBlank(scsValue)) {
            String[] sortFields = scsValue.split(",");
            List<OrderItem> orderItems=new ArrayList<>();
            for(String scStr:sortFields) {
                Matcher matcher = SC_EXTRACTION.matcher(scStr);
                if (matcher.matches()) {
                    //String field = matcher.group("field");
                    String fieldFormat = StringUtil.hump2underline(matcher.group("field"));
                    // projectYear0id1 可传入相应的id参数变为projectYear(id)
                    String field = fieldFormat.replace('0', '(').replace('1',')');
                    String o = matcher.group("sort");
                    String order = "asc".equalsIgnoreCase(o) ? "ASC" : "DESC";
                    if (StringUtil.isNotBlank(field) && StringUtil.isNotBlank(order)) {
                        OrderItem orderItem=new OrderItem();
                        orderItem.setColumn(field);
                        orderItem.setAsc("ASC".equals(order));
                        orderItems.add(orderItem);
                    }
                }
            }
            page.addOrder(orderItems);
        }
        return page;
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param entity 实体
     * @param <T>    类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query 查询条件
     * @param clazz 实体类
     * @param <T>   类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) {
        Map<String, Object> exclude = new HashMap<>(6);
        exclude.put("p", "p");
        exclude.put("s", "s");
        exclude.put("scs", "scs");
        return getQueryWrapper(query, exclude, clazz);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query   查询条件
     * @param exclude 排除的查询条件
     * @param clazz   实体类
     * @param <T>     类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Map<String, Object> exclude, Class<T> clazz) {
        exclude.forEach((k, v) -> query.remove(k));
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(BeanUtil.newInstance(clazz));
        SqlKeyword.buildCondition(query, qw);
        return qw;
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param queryContext   查询条件
     * @param <T>     类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Object entity, QueryContext queryContext, Class<T> clazz) {
        Map<String, Object> map = cn.hutool.core.bean.BeanUtil.beanToMap(entity);
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(BeanUtil.newInstance(clazz));
        SqlKeyword.buildCondition(map, qw);
        if (StringUtil.isNotBlank(queryContext.getKeyword())&& StringUtil.isNotBlank(queryContext.getKcs())){
            qw.and(tQueryWrapper -> {
                String keyword = queryContext.getKeyword();
                String kcsValue = queryContext.getKcs();
                String[] kfields = kcsValue.split(",");
                String[] kwords = keyword.split(",");
                for (int i = 0; i < kfields.length; i++) {
                    String kStr = kfields[i];
                    String keywordx = kwords[i];
                    if (i == 0) {
                        tQueryWrapper.like(kStr, keywordx);
                    } else {
                        tQueryWrapper.or().like(kStr, keywordx);
                    }
                }
            });
        }
        return qw;
    }

}
